package com.robot.matchingsystem.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

import com.robot.matchingsystem.pojo.player;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Component
public class matchingPool extends Thread{//匹配系统两个线程，一个线程不停扫描匹配池，将玩家匹配，一个线程读http请求将用户加入匹配池
    @Autowired
    RestTemplate restTemplate = new RestTemplate();
    private String startGameURL = "http://127.0.0.1:3000/pkHandle/startGame/";

    private static List<player> players = new ArrayList<>();
    private ReentrantLock lock = new ReentrantLock();

    public void addPlayer(int uid,int rating){
        lock.lock();
        try {
            players.add(new player(uid,rating,0));
        }finally {
            lock.unlock();
        }
    }
    public void removePlayer(int uid){
        lock.lock();
        try {
            players.removeIf(player -> player.getId()==uid);
        }finally {
            lock.unlock();
        }
    }
    public void increaseWaitingTime(){
        lock.lock();
        try {
            for(player i :players){
                i.setWaitingtime(i.getWaitingtime()+1);
            }
        }finally {
            lock.unlock();
        }
    }
    private boolean checkMatch(player player1,player player2){//匹配范围为waitTime*100
        int range = player1.getWaitingtime()*100;
        System.out.println(player1);
        System.out.println(player2);
        System.out.println(player2.getScore() <= player1.getScore()+range && player2.getScore()>=player1.getScore()-range);
        if(player2.getScore() <= player1.getScore()+range && player2.getScore()>=player1.getScore()-range )return true;
        else return false;
    }
    private void matchPlayers(){//遍历players,0n2算法
        for(int i=0;i< players.size();i++){
            player player = players.get(i);
            for(int j=i+1;j< players.size();j++){
                player player1 = players.get(j);
                if(checkMatch(player,player1)){
                    players.remove(player);
                    players.remove(player1);
                    sendRes(player,player1);
                    break;
                }
            }
        }
    }
    private void sendRes(player player1,player player2){//返回匹配结果，胜利得分以及失败得分
//        int K = 0;
//        System.out.println(player2);
//        System.out.println(player1);
//        int diff = Math.abs(player1.getScore() - player2.getScore());
//        int deta = 0;
//        if(diff == 0) diff = 50;
//        deta = (int) ((int) diff*(1.0 + Math.random() * 0.2));
        // 计算积分变化;
        MultiValueMap<String,String> map = new LinkedMultiValueMap<>();
        map.add("uid1",Integer.toString(player1.getId()));
        map.add("uid2",Integer.toString(player2.getId()));
        map.add("winScore","50");
        map.add("loseScore","-50");
        restTemplate.postForObject(startGameURL,map,String.class);
    }//得分机制：分差越大
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(1000);//每秒钟匹配一次
                lock.lock();
                try {
                    increaseWaitingTime();
                    matchPlayers();
                }finally {
                    lock.unlock();
                }

            } catch (InterruptedException e) {
                break;
            }

        }
    }
}
